package com.walking.configuration;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.walking.db.DataSourceName;
import com.walking.db.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author walking
 * 公众号：编程大道
 */
@Configuration
public class DynamicDataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.druid.first")
    public DataSource firstDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.second")
    public DataSource secondDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourceName.FIRST, firstDataSource);
        targetDataSources.put(DataSourceName.SECOND, secondDataSource);

        //配置包级别的数据源
        Map<String, DataSourceName> packageDataSource = new HashMap<>();
        packageDataSource.put("com.walking.service3", DataSourceName.SECOND);

        DynamicDataSource dynamicDataSource = new DynamicDataSource(firstDataSource, targetDataSources);
        dynamicDataSource.setPackageDatasource(packageDataSource);
        return dynamicDataSource;
    }

}
